import { ExecutiveContext, State,Executive, Autherizable, ActionType } from "../defination"
import { ExecutiveRecord } from "../entity"
import {  } from "../repository"
import { NEXT } from "../shared-symbols"
import { BaseAction } from "./action"
import { BeginAction } from "./beginAction"
import { invokeExecutiveAction } from "../executive"

const AUTHERIZED = Symbol("autherized")


export class AutherizeAction
<
  TActivity extends Executive<TActivity,TState,TRecord,TContext>,
  TState extends State=State,
  TRecord extends ExecutiveRecord=ExecutiveRecord,
  TContext extends ExecutiveContext=ExecutiveContext
> extends BaseAction<TActivity,TState,TRecord,TContext>
{
  [AUTHERIZED]?: boolean
  constructor(act:TActivity) {
    super(act)
  }
  get autherized(): boolean{
    return this[AUTHERIZED]===true
  }

  async invoke(context:TContext): Promise<BaseAction<TActivity,TState,TRecord,TContext>|null|undefined>{
    const result = await invokeExecutiveAction<TActivity,TState,TRecord,TContext>(this.activity,ActionType.AUTH,context)
    this[AUTHERIZED] = result===false ? false : true
    return this.next
  }

  get next(): BeginAction<TActivity,TState,TRecord,TContext>|null|undefined{
    if (this[AUTHERIZED]===undefined)
      return undefined
    
    if (this[NEXT]===undefined)  {
      if (this[AUTHERIZED]===false)
        this[NEXT] = null
      else
        this[NEXT] = new BeginAction(this)
    }
    return this[NEXT]
  }
}
